package com.example.demoshiyan03.service;

import com.example.demoshiyan03.model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;


/**
 * @author GooRay
 * 创建于 2020/5/11
 */
@EnableScheduling
@Service
public class CoronavirusDataService implements InitializingBean {

    public static String CORONA_VIRUS_DATA_URL = "https://gitee.com/gooray/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private final List<RegionStats> allRegionStats= new ArrayList<>();

    public List<RegionStats> getAllRegionStats() {
        return allRegionStats;
    }

    @Scheduled(cron="${gooray.Schedules.updateVirusDataCron}")
    public void fetchConavirusData() throws IOException{

        //爬取CSV文件
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(CORONA_VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent",""))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        //解析CSV文件
        Reader reader = new InputStreamReader(body.getInputStream());
        Iterable<CSVRecord> records = CSVFormat.DEFAULT
                .RFC4180
                .withFirstRecordAsHeader()
                .parse(reader);

        //数据存储
        for(CSVRecord record:records){
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record.get("Province/State"));
            regionStats.setCountry(record.get("Country/Region"));
            regionStats.setLatestTotalCases(Integer.parseInt(record.get(record.size()-1)));
            regionStats.setDiffFromPrevDay(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
            allRegionStats.add(regionStats);
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception{
        fetchConavirusData();
    }

}
